import {Button, ConfigProvider, message, QRCode} from "antd";
import {ArrowLeftOutlined} from "@ant-design/icons";
import React, {useState} from "react";
import {checkScan, getWechatQr} from "@/pages/user/register/service";
import {useRequest} from "@umijs/max";
import {flushSync} from "react-dom";
import {useIntl, useModel} from "@@/exports";
import wechat from './images/wechat.svg'

interface WechatLoginProps {
  onBack?: () => void
}

const WechatLogin: React.FC<WechatLoginProps> = ({
                                                   onBack
                                                 }) => {
  const {initialState, setInitialState} = useModel('@@initialState');
  const intl = useIntl();
  const [status, setStatus] = useState<'active' | 'expired' | 'loading' | 'scanned'>('active')

  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      flushSync(() => {
        setInitialState((s) => ({
          ...s,
          currentUser: userInfo,
        }));
      });
    }
  };

  const {run: runCheckScan, cancel} = useRequest(checkScan, {
    manual: true,
    pollingInterval: 2000,
    onSuccess: async (data) => {
      console.log(data)
      if (data?.isExpire) {
        setStatus('expired')
        cancel()
      }
      if (data?.isScan === true) {
        cancel()
        setStatus('scanned')
        window.localStorage.setItem('token', data?.token)
        const defaultLoginSuccessMessage = intl.formatMessage({
          id: 'pages.login.success',
          defaultMessage: '登录成功！',
        });
        message.success(defaultLoginSuccessMessage);
        await fetchUserInfo();
        const urlParams = new URL(window.location.href).searchParams;
        window.location.href = urlParams.get('redirect') || '/';
      }
    }
  })

  const {data, refresh} = useRequest(() => {
    setStatus('loading')
    return getWechatQr()
  }, {
    onSuccess: (data) => {
      if(data) {
        runCheckScan({ticket: data?.ticket})
        setStatus('active')
      }
    },
    onError() {
      setStatus('active')
    }
  })

  return <>
    <div style={{
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      flexDirection: 'column'
    }}>
      <Button icon={<ArrowLeftOutlined/>} type={'link'} onClick={() => {
        onBack?.()
      }}>切换普通登陆</Button>
      <ConfigProvider locale={{
        locale: 'zh-cn',
        QRCode: {
          scanned: '扫码成功, 即将登陆'
        }
      }}>
        <QRCode
          type={'svg'}
          icon={wechat}
          value={data?.url || window.location.href}
          onRefresh={refresh}
          status={status}/>
      </ConfigProvider>

    </div>
  </>
}

export default WechatLogin;
